package com.xuecheng.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.domain.course.response.CoursePublishResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.manage_course.dao.*;
import com.xuecheng.manage_course.feign.cms.CmsPageFeign;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CoursePublishService {
    @Resource
    CmsPageFeign cmsPageFeign;
    @Resource
    CourseBaseRepository courseBaseRepository;
    @Resource
    CoursePicRepository coursePicRepository;
    @Resource
    CourseMarketRepository courseMarketRepository;
    @Resource
    TeachplanMapper teachplanMapper;
    @Resource
    CourseViewService courseViewService;
    @Resource
    CoursePubRepository coursePubRepository;
    @Resource
    TeachplanMediaRepository teachplanMediaRepository;
    @Resource
    TeachplanMediaPubRepository teachplanMediaPubRepository;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String publish_previewUrl;
    @Value("${course-publish.pageWebPath}")
    private String publish_pageWebPath;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_pagePhysicalPath;
    @Value("${course-publish.dataUrl}")
    private String publish_dataUrl;
    /**
     * 课程发布接口,是远程调用的cms服务中的页面发布接口
     * 发布过后需要更改数据库的课程状态为202002 已发布
     * @param courseid 课程id
     * @return 发布响应结果
     */
    @Transactional
    public CoursePublishResult publish(String courseid) {
        // 准备CmsPage信息
        Optional<CourseBase> optional = courseBaseRepository.findById(courseid);
        if (!optional.isPresent()){
            ExceptionCast.cast(CourseCode.COURSE_DOES_NOT_EXIST);
        }
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(publish_siteId); // 站点id
        cmsPage.setDataUrl(publish_dataUrl+courseid); //数据url
        cmsPage.setPageName(courseid + ".html"); //课程静态文件名
        cmsPage.setPageAliase(optional.get().getName()); //静态页面名称,就是课程名
        cmsPage.setPageWebPath(publish_pageWebPath); //Web访问路径
        cmsPage.setPagePhysicalPath(publish_pagePhysicalPath); // 页面的物理路径
        cmsPage.setTemplateId(publish_templateId); //设置模板id
        CmsPostPageResult cmsPostPageResult = cmsPageFeign.postPageQuick(cmsPage);
        if (!cmsPostPageResult.isSuccess()){
            return new CoursePublishResult(CommonCode.FAIL,null);
        }
        // 更改课程状态为已发布
        CourseBase courseBase = this.saveCoursePusState(optional.get().getId());
        if (courseBase ==null){
            return new CoursePublishResult(CommonCode.FAIL,null);
        }
        // 保存Course索引信息到CoursePub数据库给ElasticSearch创建索引使用
        CoursePub coursePub = this.createCoursePub(courseid);
        coursePub.setTimestamp(new Date());
        coursePub.setTeachplan(courseViewService.getCourseView(courseid).getTeachplanNode().toString());
        coursePub.setPubTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        coursePubRepository.save(coursePub);
        // 保存课程计划信息到teachplan_media_pub数据库给ElasticSearch创建索引使用
        this.saveTeachplanMediaPub(courseid);

        // ...

        //得到url给前台
        String pageUrl = cmsPostPageResult.getPageUrl();
        return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);
    }

    // 更改课程的状态2002 已发布,发布过后课程应该选择已发布
    private CourseBase saveCoursePusState(String courseId){
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if (optional.isPresent()){
            CourseBase courseBase = optional.get();
            courseBase.setStatus("202002");
            return courseBaseRepository.save(courseBase);
        }
        return null;
    }
    /**
     * 同步课程信息到coursePub数据库,这个数据库主要聚合了course的数据
     */
    private CoursePub createCoursePub(String courseId){
        CoursePub coursePub = new CoursePub();
        // 拷贝coursebase
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(courseId);
        if (courseBaseOptional.isPresent()){
            CourseBase courseBase = courseBaseOptional.get();
            BeanUtils.copyProperties(courseBase,coursePub);
        }
        // 拷贝课程图片
        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(courseId);
        if (coursePicOptional.isPresent()){
            CoursePic coursePic = coursePicOptional.get();
            BeanUtils.copyProperties(coursePic,coursePub);
        }
        // 拷贝课程营销信息
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(courseId);
        if (courseMarketOptional.isPresent()){
            CourseMarket courseMarket = courseMarketOptional.get();
            BeanUtils.copyProperties(courseMarket,coursePub);
        }
        // 拷贝课程计划
        TeachplanNode teachplanNode = teachplanMapper.selectList(courseId);
        String s = JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(s);
        return coursePub;
    }

    private void saveTeachplanMediaPub(String courseId){
        // 先删除数据
        teachplanMediaPubRepository.deleteByCourseId(courseId);
        // 查询teachplan_media中的信息存入teachplan_media_pub
        List<TeachplanMedia> teachplanMediaList = teachplanMediaRepository.findByCourseId(courseId);
        List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();
        for (TeachplanMedia teachplanMedia : teachplanMediaList) {
            TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();
            BeanUtils.copyProperties(teachplanMedia,teachplanMediaPub);
            teachplanMediaPub.setTimestamp(new Date());
            teachplanMediaPubList.add(teachplanMediaPub);
        }
        teachplanMediaPubRepository.saveAll(teachplanMediaPubList);
    }
}
